﻿using System;
using Audio;
using Controls;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Level
{
    public class PauseState : MonoBehaviour, IState
    {
        public event Action Paused;
        public event Action Resumed;
        
        [SerializeField] private PlayerController playerController;

        private GameStateMachine _stateMachine;


        public IState Init(GameStateMachine stateMachine)
        {
            _stateMachine = stateMachine;
            return this;
        }

        public void Enter()
        {
            playerController.MenuPerformed += PlayerController_MenuPerformed;
            AudioPlayer.Instance.SetVolume(0.3f);
            
            Time.timeScale = 0f;
            playerController.SwitchControl(PlayerController.ControlType.UI);
            
            Paused?.Invoke();
        }

        public void Exit()
        {
            playerController.MenuPerformed -= PlayerController_MenuPerformed;
            AudioPlayer.Instance.SetVolume(1f);
            
            Time.timeScale = 1f;
            playerController.SwitchControl(PlayerController.ControlType.Gameplay);
            
            EventSystem.current?.SetSelectedGameObject(null);
            
            Resumed?.Invoke();
        }

        public void Resume()
        {
            _stateMachine.SwitchState<GameStartedState>();
        }
        
        private void PlayerController_MenuPerformed()
        {
            Resume();
        }
    }
}